import { createRouter, createWebHistory } from 'vue-router'
import { isLoggedIn } from '@/utils/auth'

// 路由懒加载
const Layout = () => import('@/layouts/DefaultLayout.vue')
const LoginLayout = () => import('@/layouts/LoginLayout.vue')
const Dashboard = () => import('@/views/Dashboard.vue')

// 信息管理
const Vehicles = () => import('@/views/info/Vehicles.vue')
const Drivers = () => import('@/views/info/Drivers.vue')
const FuelCards = () => import('@/views/info/FuelCards.vue')
const EtcCards = () => import('@/views/info/EtcCards.vue')
const Bindings = () => import('@/views/info/Bindings.vue')
// 移除了 Import 的导入

// 其他路由根据需要按需导入...

const routes = [
  {
    path: '/login',
    component: LoginLayout,
    meta: { title: '登录' },
    children: [
      {
        path: '',
        name: 'Login',
        component: () => import('@/views/Login.vue')
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/page',
    children: [
      {
        path: 'page',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '首页' }
      }
    ]
  },
  // 信息管理
  {
    path: '/info',
    component: Layout,
    redirect: '/info/vehicles',
    meta: { title: '信息管理' },
    children: [
      {
        path: 'vehicles',
        name: 'Vehicles',
        component: Vehicles,
        meta: { title: '车辆信息' }
      },
      {
        path: 'drivers',
        name: 'Drivers',
        component: Drivers,
        meta: { title: '驾驶员信息' }
      },
      {
        path: 'fuel-cards',
        name: 'FuelCards',
        component: FuelCards,
        meta: { title: '加油卡信息' }
      },
      {
        path: 'etc-cards',
        name: 'EtcCards',
        component: EtcCards,
        meta: { title: 'ETC卡信息' }
      },
      {
        path: 'bindings',
        name: 'Bindings',
        component: Bindings,
        meta: { title: '绑定关联' }
      }
      // 移除了 Import 路由配置
    ]
  },
  // 充值记录
  {
    path: '/recharge',
    component: Layout,
    redirect: '/recharge/fuel',
    meta: { title: '充值记录' },
    children: [
      {
        path: 'fuel',
        name: 'FuelRecharge',
        component: () => import('@/views/recharge/FuelRecharge.vue'),
        meta: { title: '加油卡充值记录' }
      },
      {
        path: 'etc',
        name: 'EtcRecharge',
        component: () => import('@/views/recharge/EtcRecharge.vue'),
        meta: { title: 'ETC卡充值记录' }
      }
    ]
  },
  // 使用记录
  {
    path: '/usage',
    component: Layout,
    redirect: '/usage/vehicle',
    meta: { title: '使用记录' },
    children: [
      {
        path: 'vehicle',
        name: 'VehicleUsage',
        component: () => import('@/views/usage/VehicleUsage.vue'),
        meta: { title: '出车记录' }
      },
      {
        path: 'fuel',
        name: 'FuelUsage',
        component: () => import('@/views/usage/FuelUsage.vue'),
        meta: { title: '加油记录' }
      },
      {
        path: 'etc',
        name: 'EtcUsage',
        component: () => import('@/views/usage/EtcUsage.vue'),
        meta: { title: 'ETC通行记录' }
      },
      {
        path: 'etc-parking',
        name: 'EtcParking',
        component: () => import('@/views/usage/EtcParking.vue'),
        meta: { title: 'ETC通停记录' }
      }
    ]
  },
  // 交通记录
  {
    path: '/traffic',
    component: Layout,
    redirect: '/traffic/violation',
    meta: { title: '交通记录' },
    children: [
      {
        path: 'violation',
        name: 'Violation',
        component: () => import('@/views/traffic/Violation.vue'),
        meta: { title: '违章记录' }
      },
      {
        path: 'accident',
        name: 'Accident',
        component: () => import('@/views/traffic/Accident.vue'),
        meta: { title: '事故记录' }
      },
      {
        path: 'insurance',
        name: 'Insurance',
        component: () => import('@/views/traffic/Insurance.vue'),
        meta: { title: '保险记录' }
      }
    ]
  },
  // 保养记录
  {
    path: '/maintenance',
    component: Layout,
    redirect: '/maintenance/service',
    meta: { title: '保养记录' },
    children: [
      {
        path: 'service',
        name: 'Service',
        component: () => import('@/views/maintenance/Service.vue'),
        meta: { title: '保养记录' }
      },
      {
        path: 'inspection',
        name: 'Inspection',
        component: () => import('@/views/maintenance/Inspection.vue'),
        meta: { title: '年检记录' }
      },
      {
        path: 'repair',
        name: 'Repair',
        component: () => import('@/views/maintenance/Repair.vue'),
        meta: { title: '维修记录' }
      }
    ]
  },
  // 制度报表
  {
    path: '/reports',
    component: Layout,
    redirect: '/reports/usage-analysis',
    meta: { title: '制度报表' },
    children: [
      {
        path: 'usage-analysis',
        name: 'UsageAnalysis',
        component: () => import('@/views/reports/UsageAnalysis.vue'),
        meta: { title: '车辆使用分析' }
      },
      {
        path: 'cost-analysis',
        name: 'CostAnalysis',
        component: () => import('@/views/reports/CostAnalysis.vue'),
        meta: { title: '成本分析' }
      },
      {
        path: 'traffic-accident',
        name: 'TrafficAccident',
        component: () => import('@/views/reports/TrafficAccident.vue'),
        meta: { title: '违章事故分析' }
      },
      {
        path: 'maintenance-analysis',
        name: 'MaintenanceAnalysis',
        component: () => import('@/views/reports/MaintenanceAnalysis.vue'),
        meta: { title: '维护分析' }
      }
    ]
  },
  // 系统管理
  {
    path: '/system',
    component: Layout,
    redirect: '/system/users',
    meta: { title: '系统管理' },
    children: [
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/system/Users.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'logs',
        name: 'Logs',
        component: () => import('@/views/system/Logs.vue'),
        meta: { title: '操作日志' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/system/Profile.vue'),
        meta: { title: '个人信息' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/system/Settings.vue'),
        meta: { title: '系统设置' }
      }
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/Error404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 车辆管理系统`
  }
  
  // 判断是否是模拟登录状态
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const isMockLogin = userInfo.name === 'Admin User' && userInfo.role === 'admin'
  
  // 判断是否需要鉴权
  // 白名单路径，不需要登录也可访问
  const whiteList = ['/login']
  
  console.log('路由导航:', {
    to: to.path,
    from: from.path,
    isLoggedIn: isLoggedIn(),
    isMockLogin,
    userInfo
  })
  
  // 已登录状态下访问登录页，直接跳转到首页
  if ((isLoggedIn() || isMockLogin) && to.path === '/login') {
    console.log('已登录状态访问登录页，重定向到首页')
    next({ path: '/page' })
    return
  }
  
  if (isMockLogin) {
    // 如果是模拟登录状态，允许访问所有页面
    console.log('模拟登录状态，允许访问:', to.path)
    next()
  } else if (!isLoggedIn() && !whiteList.includes(to.path)) {
    console.log('未登录，重定向到登录页')
    // 未登录且访问的不是白名单页面，重定向到登录页
    next({
      path: '/login',
      query: { redirect: to.fullPath } // 保存原始访问路径
    })
  } else {
    // 已登录或访问的是白名单页面
    console.log('正常导航到:', to.path)
    next()
  }
})

export default router 